package com.xayy.health.mgt.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import cn.kawins.base.result.CheckResult;
import cn.kawins.base.utils.BeanUtil;
import cn.kawins.base.utils.CollUtil;
import cn.kawins.mybatis.base.BaseServiceImpl;
import com.xayy.health.mgt.model.HealthAlgorithmManage;
import com.xayy.health.mgt.model.TaskChildInfo;
import com.xayy.health.mgt.model.TaskInfo;
import com.xayy.health.mgt.model.TaskParamInfo;
import com.xayy.health.mgt.model.dto.TelemetryDto;
import com.xayy.health.mgt.model.vo.PreprocessParamVo;
import com.xayy.health.mgt.service.HealthAlgorithmManageService;
import com.xayy.health.mgt.service.TaskChildInfoService;
import com.xayy.health.mgt.service.TaskInfoService;
import com.xayy.health.mgt.service.TaskParamInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author Nie
 * @version V1.0
 * @date 2023/7/26 16:32
 */
@Service
public class TaskParamInfoServiceImpl extends BaseServiceImpl<TaskParamInfo> implements TaskParamInfoService {

    @Autowired
    private TaskInfoService taskInfoService;
    @Autowired
    private HealthAlgorithmManageService manageService;
    @Autowired
    private TaskChildInfoService taskChildInfoService;

    @Override
    public CheckResult<Object> checkTask(TelemetryDto telemetryDto) {
        List<TaskInfo> taskInfoList = taskInfoService.select(TaskInfo.builder().satelliteCode(telemetryDto.getSatelliteCode()).name(telemetryDto.getName()).type(1).build());
        if(!taskInfoList.isEmpty()){
            return CheckResult.fail("任务名称与任务列表中重复,请修改任务名称");
        }
        List<String> messages = new ArrayList<>();
        String[] paramCodes = telemetryDto.getParamCodes();
        for (String code : paramCodes) {
            TaskParamInfo taskParamInfo = selectOne(TaskParamInfo.builder()
                .satelliteCode(telemetryDto.getSatelliteCode()).paramCode(code).status(1).build());
            if (BeanUtil.isNotEmpty(taskParamInfo)) {
                String message = "参数: " + code + "在任务[" + taskParamInfo.getTaskName() + "]中存在;";
                messages.add(message);
            }
        }
        if (CollUtil.isNotEmpty(messages)) {
            StrBuilder msg = new StrBuilder();
            for (String message : messages) {
                msg.append(message);
            }
            msg.append("确认继续将以上任务的数据覆盖,是否继续?");
            return CheckResult.success(msg.toString());
        }
        return CheckResult.success();
    }

    @Override
    public void updateStatus(TaskInfo taskInfo) {
        String[] paramCodes = taskInfo.getParams().split(",");
        Example example = new Example(TaskParamInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("paramCode", Arrays.asList(paramCodes));
        criteria.andEqualTo("status", 1);
        List<TaskParamInfo> taskParamInfos = selectByExample(example);
        if (CollUtil.isNotEmpty(taskParamInfos)) {
            taskParamInfos.forEach(x -> x.setStatus(0));
            updateListById(taskParamInfos);
        }
    }

    @Override
    public CheckResult<Object> insertInfos(TaskInfo taskInfo) {
        String[] paramCodes = taskInfo.getParams().split(",");
        // 获取剔野、填充、平滑算法名称
        String tyName = null;
        String tcName = null;
        String phName = null;
        String tyTag = taskInfo.getTyTag();
        if (StrUtil.isNotBlank(tyTag)) {
            HealthAlgorithmManage tyAlgorithm =
                manageService.selectOne(HealthAlgorithmManage.builder().algorithmCode(tyTag).build());
            tyName = tyAlgorithm.getAlgorithmName();
        }
        String tcTag = taskInfo.getTcTag();
        if (StrUtil.isNotBlank(tcTag)) {
            HealthAlgorithmManage tcAlgorithm =
                manageService.selectOne(HealthAlgorithmManage.builder().algorithmCode(tcTag).build());
            tcName = tcAlgorithm.getAlgorithmName();
        }
        String phTag = taskInfo.getPhTag();
        if (StrUtil.isNotBlank(phTag)) {
            HealthAlgorithmManage phAlgorithm =
                manageService.selectOne(HealthAlgorithmManage.builder().algorithmCode(phTag).build());
            phName = phAlgorithm.getAlgorithmName();
        }

        List<TaskParamInfo> paramInfos = new ArrayList<>();
        for (String paramCode : paramCodes) {
            TaskParamInfo taskParamInfo = new TaskParamInfo();
            taskParamInfo.setId(null);
            taskParamInfo.setSatelliteCode(taskInfo.getSatelliteCode());
            taskParamInfo.setTaskId(taskInfo.getId());
            taskParamInfo.setTaskName(taskInfo.getName());
            taskParamInfo.setParamCode(paramCode);
            taskParamInfo.setTyName(tyName);
            taskParamInfo.setTcName(tcName);
            taskParamInfo.setPhName(phName);
            taskParamInfo.setStatus(1);
            paramInfos.add(taskParamInfo);
        }
        insertList(paramInfos);
        return CheckResult.success();
    }

    @Override
    public CheckResult<Object> preprocessParam(PreprocessParamVo preprocessParamVo) {
        StrBuilder msg = new StrBuilder();
        TaskParamInfo taskParamInfo =
            selectOne(TaskParamInfo.builder().satelliteCode(preprocessParamVo.getSatelliteCode())
                .paramCode(preprocessParamVo.getParamCode()).status(1).build());
        if (BeanUtil.isNotEmpty(taskParamInfo)) {
            TaskInfo taskInfo = taskInfoService.selectById(taskParamInfo.getTaskId());
            Date startTime = taskInfo.getStartTime();
            Date endTime = taskInfo.getEndTime();
            String startTimeStr = DateUtil.format(startTime, "yyyy-MM-dd HH:mm:ss");
            String endTimeStr = DateUtil.format(endTime, "yyyy-MM-dd HH:mm:ss");
            msg.append("参数：").append(preprocessParamVo.getParamCode()).append("在数据预处理任务：").append(taskInfo.getName())
                .append("；时间段：").append(startTimeStr).append("--").append(endTimeStr).append("；中进行了预处理");
            if (StrUtil.isNotBlank(taskParamInfo.getTyName())) {
                msg.append("，使用剔野算法为：");
                msg.append(taskParamInfo.getTyName());
            }
            if (StrUtil.isNotBlank(taskParamInfo.getTcName())) {
                msg.append("，使用填充算法为：");
                msg.append(taskParamInfo.getTcName());
            }
            if (StrUtil.isNotBlank(taskParamInfo.getPhName())) {
                msg.append("，使用平滑算法为：");
                msg.append(taskParamInfo.getPhName());
            }
            List<TaskChildInfo> childInfo = taskChildInfoService.select(TaskChildInfo.builder().taskId(taskInfo.getId()).status(4).build());
            if(CollUtil.isNotEmpty(childInfo)){
                msg.append("【以下时间段被清除");
                for (TaskChildInfo taskChildInfo : childInfo) {
                    if(taskChildInfo.getStatus()==4){
                        msg.append(DateUtil.format(taskChildInfo.getStartTime(), "yyyy-MM-dd HH:mm:ss")).append("到").append(DateUtil.format(taskChildInfo.getEndTime(), "yyyy-MM-dd HH:mm:ss")).append(",");
                    }
                }
                msg.append("】");
            }
        }else {
            msg.append("参数：").append(preprocessParamVo.getParamCode()).append("未进行过数据预处理");
        }

        return CheckResult.success(msg.toString());
    }

}
